import axios from 'axios'
import { ElMessage } from 'element-plus'
import router  from '@/router';//引入路由
const service = axios.create({
  timeout: 60000,
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加请求头等前置处理
    config.headers['Authorization'] = localStorage.getItem('token')
    return config
  },
  error => {
    // 请求错误处理
    console.log('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 响应后处理
    if (response.status === 200 && response.data.code === 200) {
      if(response.data.msg!==null && response.data.msg!==undefined&&response.data.msg!==''){
        ElMessage.success(response.data.msg)
      }
      return Promise.resolve(response.data)
    }else if(response.data.type==='application/zip'){
        //下载文件
        return Promise.resolve(response.data)
    }else if(response.data.code === 501){
      //密码错误
      return Promise.resolve(response)
    }else if(response.data.code === 401){
      //token失效
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      ElMessage.error(response.data.msg)
      router.replace('/login/form')
      return Promise.reject(response)
    }
    else {
      // 错误提示
      ElMessage.error(response.data.msg)
      return Promise.reject(response.data)
    }
  },
  error => {
    let errorMsg = '服务器无响应，请检查网络连接'
    ElMessage.error(errorMsg)
    return Promise.reject(error)
  }
)

export default service
